<template>
  <div class="email-reverse-check-container">
    <!-- 顶部栏与侧边栏将由MainHeader和SideMenu组件提供 -->
    <MainHeader />
    
    <div class="main-container">
      <!-- 左侧导航 -->
      <SideMenu />
      
      <!-- 主内容区域 -->
      <div class="content-container">
        <div class="search-content">
          <div class="page-header">
            <div class="title">{{ t('email.reverse.title') }}</div>
            <div class="description">
              {{ t('email.reverse.description') }}
            </div>
          </div>
          
          <div class="search-actions">
            <el-button :type="searchType === 'email' ? 'primary' : 'default'" class="action-button" @click="searchType = 'email'">
              <el-icon><Message /></el-icon>
              {{ t('email.reverse.email.check') }}
            </el-button>
            
            <el-button :type="searchType === 'phone' ? 'primary' : 'default'" class="action-button" @click="searchType = 'phone'">
              <el-icon><Phone /></el-icon>
              {{ t('email.reverse.phone.check') }}
            </el-button>
          </div>
          
          <div class="search-box">
            <el-input
              :placeholder="searchType === 'email' ? t('email.reverse.email.placeholder') : t('email.reverse.phone.placeholder')"
              v-model="searchKeyword"
              class="search-input"
              clearable
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            
            <el-button type="primary" class="search-button" @click="handleSearch">{{ t('email.reverse.search.button') }}</el-button>
            <el-button type="success" class="action-button batch-search-btn" @click="showBatchDialog = true">
              <el-icon :size="18"><Upload /></el-icon>
              {{ getCurrentLanguage() === 'zh' ? '批量反查' : 'Batch Reverse' }}
            </el-button>
          </div>
          
          <!-- API错误信息 -->
          <div v-if="apiError" class="api-error-alert">
            <el-alert
              type="error"
              :description="`请求失败: ${apiError}。`"
              show-icon
              closable
            />
          </div>
          
          <!-- 搜索结果区域 -->
          <div class="search-results" v-if="searchResults.length">
            <div class="results-header">
              <h3>{{ t('email.reverse.results') }} ({{ searchResults.length }}条)</h3>
              <el-button size="small" @click="clearResults">{{ t('email.reverse.return') }}</el-button>
            </div>
            
            <div class="result-cards">
              <div v-for="(result, index) in searchResults" :key="index" class="result-card">
                <div class="result-header">
                  <h4>{{ result.name || result.company_name || result.Full_name || 
                       result.exhibitor_name || result.Company_Name || t('email.reverse.unknown') }}</h4>
                  <div class="result-source">{{ getSourceName(result.source) }}</div>
                </div>
                
                <div class="result-content">
                  <!-- 展示所有非空字段 -->
                  <template v-for="(value, key) in getFilteredFields(result)" :key="key">
                    <div class="info-row">
                      <span class="info-label">{{ getFieldLabel(key) }}:</span>
                      <span class="info-value" :class="{ highlight: key === 'email' || key === 'Emails' || key === 'phone' || key === 'Phone_numbers' || key === 'mobile_phone' || key === 'telephone' }">
                        {{ value }}
                      </span>
                      <el-button v-if="key === 'email' || key === 'Emails' || key === 'phone' || key === 'Phone_numbers' || key === 'mobile_phone' || key === 'telephone'" 
                                 size="small" 
                                 @click="copyToClipboard(value)" 
                                 class="copy-btn">{{ t('email.reverse.copy') }}</el-button>
                    </div>
                  </template>
                </div>
              </div>
            </div>
            
            <!-- 加载更多按钮 -->
            <div class="load-more" v-if="searchResults.length < totalResults">
              <el-button type="primary" plain @click="loadMore" :loading="loading">{{ t('email.reverse.load.more') }}</el-button>
            </div>
          </div>
          
          <!-- 无搜索结果 -->
          <div class="no-results" v-if="searched && !searchResults.length && !apiError">
            <el-empty :description="t('email.reverse.no.results')"></el-empty>
          </div>
          
          <!-- 加载状态 -->
          <div class="loading-container" v-if="loading">
            <el-skeleton :rows="5" animated />
          </div>
          
          <!-- 功能介绍卡片，仅在没有搜索结果且未搜索时显示 -->
          <div class="feature-cards" v-if="!searchResults.length && !searched">
            <div class="feature-card">
              <div class="icon">
                <el-icon :size="40" class="blue-icon"><Message /></el-icon>
              </div>
              <div class="card-content">
                <div class="card-title">{{ t('email.reverse.feature.email') }}</div>
                <div class="card-desc">{{ t('email.reverse.feature.email.desc') }}</div>
              </div>
            </div>
            
            <div class="feature-card">
              <div class="icon">
                <el-icon :size="40" class="green-icon"><CircleCheck /></el-icon>
              </div>
              <div class="card-content">
                <div class="card-title">{{ t('email.reverse.feature.phone') }}</div>
                <div class="card-desc">{{ t('email.reverse.feature.phone.desc') }}</div>
              </div>
            </div>
            
            <div class="feature-card">
              <div class="icon">
                <el-icon :size="40" class="purple-icon"><Compass /></el-icon>
              </div>
              <div class="card-content">
                <div class="card-title">{{ t('email.reverse.feature.multi.source') }}</div>
                <div class="card-desc">{{ t('email.reverse.feature.multi.source.desc') }}</div>
              </div>
            </div>
            
            <div class="feature-card">
              <div class="icon">
                <el-icon :size="40" class="orange-icon"><Promotion /></el-icon>
              </div>
              <div class="card-content">
                <div class="card-title">{{ t('email.reverse.feature.export') }}</div>
                <div class="card-desc">{{ t('email.reverse.feature.export.desc') }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 批量反查对话框 -->
    <el-dialog
      v-model="showBatchDialog"
      :title="getCurrentLanguage() === 'zh' ? '批量邮件反查' : 'Batch Email Reverse Check'"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="batch-dialog-content">
        
        <el-alert
          :title="getCurrentLanguage() === 'zh' ? '使用说明' : 'Instructions'"
          type="info"
          :closable="false"
          style="margin-bottom: 20px;"
        >
          <template #default>
            <div v-if="getCurrentLanguage() === 'zh'">
              <p>1. 请上传包含Email（邮箱）或Phone（电话）列的Excel文件</p>
              <p>2. 系统将自动识别表头类型（邮箱或电话）并进行反查</p>
              <p>3. 系统将在6个数据源中搜索匹配数据：Facebook、Twitter、LinkedIn、全球企业库、广交会采购商、广交会展商</p>
              <p>4. 搜索结果将自动下载为Excel文件，每个数据源对应一个工作表</p>
              <p>5. 只有包含数据的数据源才会生成工作表，无数据的数据源会自动跳过</p>
            </div>
            <div v-else>
              <p>1. Please upload an Excel file with an Email or Phone column</p>
              <p>2. The system will automatically identify the header type (email or phone) and perform reverse lookup</p>
              <p>3. The system will search 6 data sources: Facebook, Twitter, LinkedIn, Global Enterprise, Canton Fair Buyers, Canton Fair Exhibitors</p>
              <p>4. Results will be automatically downloaded as an Excel file with separate sheets for each data source</p>
              <p>5. Only data sources with results will generate worksheets, empty sources will be skipped</p>
            </div>
          </template>
        </el-alert>
        
        <!-- 文件上传 -->
        <el-upload
          ref="uploadRef"
          class="upload-demo"
          drag
          :auto-upload="false"
          :limit="1"
          :on-change="handleFileChange"
          :on-exceed="handleExceed"
          accept=".xlsx,.xls"
          :file-list="fileList"
        >
          <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
          <div class="el-upload__text">
            {{ getCurrentLanguage() === 'zh' ? '将Excel文件拖到此处，或' : 'Drop Excel file here or' }}
            <em>{{ getCurrentLanguage() === 'zh' ? '点击上传' : 'click to upload' }}</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              {{ getCurrentLanguage() === 'zh' ? '仅支持 .xlsx 和 .xls 格式的文件' : 'Only .xlsx and .xls files are supported' }}
            </div>
          </template>
        </el-upload>
        
        <!-- 进度条 -->
        <div v-if="batchUploading" style="margin-top: 20px;">
          <el-progress :percentage="uploadProgress" :status="uploadStatus"></el-progress>
          <div style="text-align: center; margin-top: 10px; color: #606266;">
            {{ uploadStatusText }}
          </div>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button type="warning" plain @click="downloadTemplate('email')">
            <el-icon><Download /></el-icon>
            {{ getCurrentLanguage() === 'zh' ? '下载邮箱模板' : 'Email Template' }}
          </el-button>
          <el-button type="warning" plain @click="downloadTemplate('phone')" style="margin-left: 10px;">
            <el-icon><Download /></el-icon>
            {{ getCurrentLanguage() === 'zh' ? '下载电话模板' : 'Phone Template' }}
          </el-button>

          <el-button @click="cancelBatchUpload">
            {{ getCurrentLanguage() === 'zh' ? '取消' : 'Cancel' }}
          </el-button>
          <el-button
            type="primary"
            @click="submitBatchReverse"
            :loading="batchUploading"
            :disabled="!selectedFile"
          >
            {{ getCurrentLanguage() === 'zh' ? '开始反查' : 'Start Reverse' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { Search, Phone, Message, CircleCheck, Compass, Promotion, Document, Delete, Upload, UploadFilled, Download } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import MainHeader from '@/components/MainHeader.vue'
import SideMenu from '@/components/SideMenu.vue'
import { useRouter } from 'vue-router'
import { t, getCurrentLanguage } from '@/utils/i18n'

// 定义响应式数据
const searchType = ref('email') // email 或 phone
const searchKeyword = ref('')
const searchResults = ref([])
const loading = ref(false)
const searched = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const totalResults = ref(0)
const apiError = ref(null)
const router = useRouter()

// 批量反查相关数据
const showBatchDialog = ref(false)
const selectedFile = ref(null)
const fileList = ref([])
const uploadRef = ref(null)
const batchUploading = ref(false)
const uploadProgress = ref(0)
const uploadStatus = ref('')
const uploadStatusText = ref('')

// 实际搜索函数
const handleSearch = async () => {
  if (!searchKeyword.value.trim()) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.warning(searchType.value === 'email' ? '请输入邮箱地址' : '请输入电话号码')
    } else {
      ElMessage.warning(searchType.value === 'email' ? 'Please enter an email address' : 'Please enter a phone number')
    }
      return
  }
  
  // 检查是否有token
  const token = localStorage.getItem('token')
  if (!token) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.warning('您尚未登录，请先登录后再进行查询')
    } else {
      ElMessage.warning('You are not logged in, please log in first before searching')
    }
    // 保存当前路径用于登录后重定向
    localStorage.setItem('redirectPath', '/email-reverse-check')
    // 跳转到登录页
    router.push('/login')
    return
  }
  
  // 统计真实搜索次数
  let count = parseInt(localStorage.getItem('searchCount_emailReverse') || '0')
  localStorage.setItem('searchCount_emailReverse', count + 1)
  
  loading.value = true
  searched.value = true
  currentPage.value = 1
  apiError.value = null
  
  try {
    const response = await axios.get('/api/email-lookup', {
      params: {
        value: searchKeyword.value,
        type: searchType.value,
        page: currentPage.value,
        size: pageSize.value
      },
      headers: {
        'Authorization': `Bearer ${token}`  // 确保请求携带token
      },
      // 添加超时设置
      timeout: 30000
    });
    
    if (response.data && typeof response.data === 'object') {
      searchResults.value = response.data.results || [];
      totalResults.value = response.data.total || 0;
      
      // 检查是否返回了错误信息
      if (response.data.error) {
        apiError.value = response.data.error;
        if (getCurrentLanguage() === 'zh') {
          ElMessage.error(`搜索出现错误: ${response.data.error}`);
        } else {
          ElMessage.error(`Search failed`);
        }
      }
    } else {
      apiError.value = '服务器返回的数据格式不正确';
      if (getCurrentLanguage() === 'zh') {
        ElMessage.error('服务器返回的数据格式不正确');
      } else {
        ElMessage.error('Server returned data in an incorrect format');
      }
      searchResults.value = [];
      totalResults.value = 0;
    }
  } catch (error) {

    // 详细的错误处理
    if (error.response) {
      // 服务器返回了错误状态码
      const status = error.response.status;
      apiError.value = `服务器返回错误(${status}): ${error.response.data?.message || error.message || '未知错误'}`;
    } else if (error.request) {
      // 请求已发出，但没有收到响应
      apiError.value = '服务器未响应，请检查后端服务是否正常运行';
    } else {
      // 请求设置触发的错误
      apiError.value = `请求错误: ${error.message}`;
    }

    if (getCurrentLanguage() === 'zh') {
      ElMessage.error(`搜索失败: ${apiError.value}`);
    } else {
      ElMessage.error(`Search failed`);
    }
    searchResults.value = [];
    totalResults.value = 0;
  } finally {
    loading.value = false;
  }
};

// 加载更多结果
const loadMore = async () => {
  if (searchResults.value.length >= totalResults.value) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.info('已加载全部数据');
    } else {
      ElMessage.info('All data has been loaded');
    }
    return;
  }
  
  // 获取token
  const token = localStorage.getItem('token')
  if (!token) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.warning('您的登录已过期，请重新登录')
    } else {
      ElMessage.warning('Your login has expired, please log in again')
    }
    router.push('/login')
    return
  }

  loading.value = true;
  currentPage.value += 1;
  
  try {
    
    const response = await axios.get('/api/email-lookup', {
      params: {
        value: searchKeyword.value,
        type: searchType.value,
        page: currentPage.value,
        size: pageSize.value
      },
      headers: {
        'Authorization': `Bearer ${token}`  // 确保请求携带token
      }
    });
    
    const newResults = response.data.results || [];
    searchResults.value = [...searchResults.value, ...newResults];
  } catch (error) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.error(`加载更多失败: ${error.message || '服务器连接失败'}`);
    } else {
      ElMessage.error(`Failed to load more`);
    }
    currentPage.value -= 1;
  } finally {
    loading.value = false;
  }
};

// 清除搜索结果
const clearResults = () => {
  searchResults.value = [];
  searched.value = false;
  currentPage.value = 1;
  totalResults.value = 0;
  apiError.value = null;
};

// 复制到剪贴板
const copyToClipboard = (text) => {
  navigator.clipboard.writeText(text)
    .then(() => {
      if (getCurrentLanguage() === 'zh') {
        ElMessage.success('已复制到剪贴板');
      } else {
        ElMessage.success('Copied to clipboard');
      }
    })
    .catch(() => {
       if (getCurrentLanguage() === 'zh') {
         ElMessage.error('复制失败，请手动复制');
       } else {
         ElMessage.error('Copy failed, please manually copy');
       }
    });
};

// 获取数据源名称
const getSourceName = (source) => {
  const sourceMap = {
    'canton_fair_exhibitors': t('email.reverse.source.canton.exhibitor'),
    'canton_fair_purchasers': t('email.reverse.source.canton.purchaser'),
    'facebook_data': t('email.reverse.source.facebook'),
    'global_enterprise_library': t('email.reverse.source.enterprise'),
    'linkedin_data': t('email.reverse.source.linkedin'),
    'users': t('email.reverse.source.users')
  };
  return sourceMap[source] || t('email.reverse.source.unknown');
};

// 过滤掉空字段和source字段
const getFilteredFields = (result) => {
  const filteredObj = {};
  Object.entries(result).forEach(([key, value]) => {
    if (value !== null && value !== undefined && value !== '' && key !== 'source') {
      filteredObj[key] = value;
    }
  });
  return filteredObj;
};

// 获取字段名称的标签（支持中英文切换）
const getFieldLabel = (key) => {
  // 定义字段翻译映射表
  const fieldTranslations = {
    // 您提到的核心字段
    'birth_date': { zh: '出生日期', en: 'Birth Date' },
    'birth_place': { zh: '出生地', en: 'Birth Place' },
    'work_place': { zh: '工作地点', en: 'Workplace' },
    'workplace_city': { zh: '工作城市', en: 'Workplace City' },
    'uid': { zh: '用户ID', en: 'User ID' },
    'phone_number': { zh: '电话号码', en: 'Phone Number' },
    'join_date': { zh: '加入日期', en: 'Join Date' },
    'id': { zh: 'ID', en: 'ID' },

    // 基本字段
    'first_name': { zh: '名', en: 'First Name' },
    'last_name': { zh: '姓', en: 'Last Name' },
    'gender': { zh: '性别', en: 'Gender' },
    'email': { zh: '邮箱', en: 'Email' },
    'phone': { zh: '电话', en: 'Phone' },
    'name': { zh: '姓名', en: 'Name' },
    'location': { zh: '位置', en: 'Location' },
    'industry': { zh: '行业', en: 'Industry' },
    'position': { zh: '职位', en: 'Position' },
    'title': { zh: '职位', en: 'Title' },
    'company_name': { zh: '公司名称', en: 'Company Name' },
    'country': { zh: '国家', en: 'Country' },
    'dob': { zh: '出生日期', en: 'Date of Birth' },

    // LinkedIn字段
    'Full_name': { zh: '全名', en: 'Full Name' },
    'Job_title': { zh: '职位头衔', en: 'Job Title' },
    'Company_Name': { zh: '公司名称', en: 'Company Name' },
    'Phone_numbers': { zh: '电话号码', en: 'Phone Numbers' },
    'Emails': { zh: '邮箱', en: 'Emails' },
    'First_Name': { zh: '名', en: 'First Name' },
    'Last_Name': { zh: '姓', en: 'Last Name' },
    'Gender': { zh: '性别', en: 'Gender' },
    'Middle_Name': { zh: '中间名', en: 'Middle Name' },

    // 中文字段名
    '名': { zh: '名', en: 'First Name' },
    '姓': { zh: '姓', en: 'Last Name' },
    '性别': { zh: '性别', en: 'Gender' },
    '邮箱': { zh: '邮箱', en: 'Email' },

    // 其他常用字段
    'mobile_phone': { zh: '手机', en: 'Mobile Phone' },
    'telephone': { zh: '电话', en: 'Telephone' },
    'web_address': { zh: '网站', en: 'Website' },
    'mailing_address': { zh: '邮寄地址', en: 'Mailing Address' },
    'primary_city': { zh: '主要城市', en: 'Primary City' },
    'primary_state': { zh: '主要州', en: 'Primary State' },
    'zip_code': { zh: '邮政编码', en: 'Zip Code' },
    'middle_name': { zh: '中间名', en: 'Middle Name' }
  };

  // 获取当前语言
  const currentLang = getCurrentLanguage();
  const langKey = currentLang === 'en' ? 'en' : 'zh';

  // 如果有对应的翻译，返回翻译
  if (fieldTranslations[key]) {
    return fieldTranslations[key][langKey];
  }

  // 如果没有找到翻译，使用后备映射表（只包含未翻译的字段）
  const fallbackMap = {
    // 其他未在上面定义的字段（保持中文，因为这些字段较少使用）
    'reveneu': '收入',
    'employee': '员工规模',
    'sub_industry': '子行业',
    'country_region': '国家/地区',
    'procurement_product_type': '采购产品类型',
    'contact_team': '联系团队',
    'contact_way': '联系方式',
    'fax': '传真',
    'address': '地址',
    'website': '网站',
    'exhibitor_name': '展商名称',
    'booth_number': '展位号',
    'contact_person': '联系人',
    'province': '省份',
    'city': '城市',
    'postal_code': '邮编',
    'main_products': '主营产品',
    'main_keywords': '主营关键词',
    'establishment_year': '成立时间',
    'registered_capital': '注册资金',
    'enterprise_scale': '企业规模',
    'enterprise_type': '企业类型',
    'trade_form': '贸易形式',
    'exhibition_history': '参展历史',
    'enterprise_nature': '企业性质',
    'email_address': '电子邮箱',
    'product': '产品',
    'session': '届数',
    'Sub_Role': '子角色',
    'Industry_2': '第二行业',
    'Mobile': '手机',
    'Company_Industry': '公司行业',
    'Company_Website': '公司网站',
    'Company_Size': '公司规模',
    'Company_Founded': '公司成立年份',
    'Skills': '技能',
    'Middle_Initial': '中间名首字母',
    'LinkedIn_Url': '领英网址',
    'LinkedIn_Username': '领英用户名',
    'snapchat_username': 'Snapchat用户名'
  };

  // 检查后备映射表
  if (fallbackMap[key]) {
    return fallbackMap[key];
  }

  // 如果都没有找到，返回原始键名
  return key;
};

// 批量反查相关方法
// 文件选择变化
const handleFileChange = (file, fileListParam) => {
  selectedFile.value = file.raw;
  fileList.value = fileListParam;
};

// 文件超出限制
const handleExceed = () => {
  if (getCurrentLanguage() === 'zh') {
    ElMessage.warning('只能上传一个文件，请先移除已选文件');
  } else {
    ElMessage.warning('Only one file can be uploaded, please remove the selected file first');
  }
};

// 取消批量上传
const cancelBatchUpload = () => {
  if (batchUploading.value) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.warning('反查正在进行中，请稍后再试');
    } else {
      ElMessage.warning('Reverse check is in progress, please try again later');
    }
    return;
  }
  
  showBatchDialog.value = false;
  selectedFile.value = null;
  fileList.value = [];
  uploadProgress.value = 0;
  uploadStatus.value = '';
  uploadStatusText.value = '';
};

// 提交批量反查
const submitBatchReverse = async () => {
  if (!selectedFile.value) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.warning('请先选择要上传的Excel文件');
    } else {
      ElMessage.warning('Please select an Excel file to upload first');
    }
    return;
  }

  // 检查文件格式
  const fileName = selectedFile.value.name;
  if (!fileName.endsWith('.xlsx') && !fileName.endsWith('.xls')) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.error('文件格式不正确，只支持.xlsx和.xls格式');
    } else {
      ElMessage.error('Invalid file format, only .xlsx and .xls are supported');
    }
    return;
  }

  // 检查token
  const token = localStorage.getItem('token');
  if (!token) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.warning('您尚未登录，请先登录');
    } else {
      ElMessage.warning('You are not logged in, please log in first');
    }
    router.push('/login');
    return;
  }

  // 准备FormData
  const formData = new FormData();
  formData.append('file', selectedFile.value);

  batchUploading.value = true;
  uploadProgress.value = 0;
  uploadStatus.value = '';
  
  if (getCurrentLanguage() === 'zh') {
    uploadStatusText.value = '正在上传文件...';
  } else {
    uploadStatusText.value = 'Uploading file...';
  }

  try {
    const response = await axios.post('/api/email-reverse-check/batch', formData, {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'multipart/form-data'
      },
      responseType: 'blob', // 重要：接收二进制数据
      timeout: 900000, // 15分钟超时（批量反查数据量大时需要更长时间）
      onUploadProgress: (progressEvent) => {
        // 上传进度
        if (progressEvent.total) {
          uploadProgress.value = Math.round((progressEvent.loaded * 50) / progressEvent.total);
        }
      },
      onDownloadProgress: (progressEvent) => {
        // 下载进度
        if (progressEvent.total) {
          const downloadProgress = Math.round((progressEvent.loaded * 50) / progressEvent.total);
          uploadProgress.value = 50 + downloadProgress;
        } else {
          uploadProgress.value = 75;
        }
        
        if (getCurrentLanguage() === 'zh') {
          uploadStatusText.value = '正在处理反查结果...';
        } else {
          uploadStatusText.value = 'Processing reverse check results...';
        }
      }
    });

    // 检查响应是否为错误JSON（而非Excel文件）
    if (response.data.type === 'application/json') {
      // 说明返回的是错误信息
      const reader = new FileReader();
      reader.onload = (e) => {
        try {
          const errorData = JSON.parse(e.target.result);
          const errorMsg = errorData.msg || errorData.message || '批量反查失败';
          if (getCurrentLanguage() === 'zh') {
            ElMessage.error(errorMsg);
          } else {
            ElMessage.error(errorData.msg || errorData.message || 'Batch reverse check failed');
          }
        } catch (parseError) {
          if (getCurrentLanguage() === 'zh') {
            ElMessage.error('服务器返回了未知错误');
          } else {
            ElMessage.error('Server returned an unknown error');
          }
        }
      };
      reader.readAsText(response.data);
      
      uploadProgress.value = 0;
      uploadStatus.value = 'exception';
      if (getCurrentLanguage() === 'zh') {
        uploadStatusText.value = '反查失败';
      } else {
        uploadStatusText.value = 'Reverse check failed';
      }
      return;
    }

    // 成功接收到Excel文件，触发下载
    uploadProgress.value = 100;
    uploadStatus.value = 'success';
    if (getCurrentLanguage() === 'zh') {
      uploadStatusText.value = '反查完成，正在下载...';
    } else {
      uploadStatusText.value = 'Reverse check completed, downloading...';
    }
    
    const blob = new Blob([response.data], { 
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
    });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    
    // 从响应头获取文件名，如果没有则使用默认名称
    const contentDisposition = response.headers['content-disposition'];
    let filename = `批量邮件反查结果_${new Date().getTime()}.xlsx`;
    if (contentDisposition) {
      const filenameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
      if (filenameMatch && filenameMatch[1]) {
        filename = decodeURIComponent(filenameMatch[1].replace(/['"]/g, ''));
      }
    }
    
    link.setAttribute('download', filename);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);

    if (getCurrentLanguage() === 'zh') {
      ElMessage.success('批量反查完成，结果已下载');
    } else {
      ElMessage.success('Batch reverse check completed, results downloaded');
    }
    
    // 重置状态
    setTimeout(() => {
      showBatchDialog.value = false;
      selectedFile.value = null;
      fileList.value = [];
      uploadProgress.value = 0;
      uploadStatus.value = '';
      uploadStatusText.value = '';
    }, 1500);

  } catch (error) {
    console.error('批量反查错误:', error);
    
    uploadProgress.value = 0;
    uploadStatus.value = 'exception';
    
    if (error.response) {
      // 服务器返回了错误
      if (error.response.status === 400) {
        // 尝试解析错误消息
        try {
          const errorBlob = error.response.data;
          const reader = new FileReader();
          reader.onload = (e) => {
            try {
              const errorData = JSON.parse(e.target.result);
              const errorMsg = errorData.msg || errorData.message || '批量反查失败';
              if (getCurrentLanguage() === 'zh') {
                ElMessage.error(errorMsg);
                uploadStatusText.value = errorMsg;
              } else {
                ElMessage.error(errorData.msg || errorData.message || 'Batch reverse check failed');
                uploadStatusText.value = errorData.msg || errorData.message || 'Reverse check failed';
              }
            } catch (parseError) {
              if (getCurrentLanguage() === 'zh') {
                ElMessage.error('批量反查失败，请检查文件格式');
                uploadStatusText.value = '反查失败';
              } else {
                ElMessage.error('Batch reverse check failed, please check file format');
                uploadStatusText.value = 'Reverse check failed';
              }
            }
          };
          reader.readAsText(errorBlob);
        } catch (e) {
          if (getCurrentLanguage() === 'zh') {
            ElMessage.error('批量反查失败，请检查文件格式');
            uploadStatusText.value = '反查失败';
          } else {
            ElMessage.error('Batch reverse check failed, please check file format');
            uploadStatusText.value = 'Reverse check failed';
          }
        }
      } else {
        if (getCurrentLanguage() === 'zh') {
          ElMessage.error(`服务器错误 (${error.response.status})`);
          uploadStatusText.value = `服务器错误 (${error.response.status})`;
        } else {
          ElMessage.error(`Server error (${error.response.status})`);
          uploadStatusText.value = `Server error (${error.response.status})`;
        }
      }
    } else if (error.request) {
      if (getCurrentLanguage() === 'zh') {
        ElMessage.error('服务器未响应，请检查网络连接');
        uploadStatusText.value = '服务器未响应';
      } else {
        ElMessage.error('No response from server, please check network');
        uploadStatusText.value = 'No server response';
      }
    } else {
      if (getCurrentLanguage() === 'zh') {
        ElMessage.error('请求失败: ' + error.message);
        uploadStatusText.value = '请求失败';
      } else {
        ElMessage.error('Request failed: ' + error.message);
        uploadStatusText.value = 'Request failed';
      }
    }
  } finally {
    batchUploading.value = false;
  }
};

// 下载模板
const downloadTemplate = async (type) => {
  const lang = getCurrentLanguage();
  const token = localStorage.getItem('token');
  
  try {
    const response = await axios.get('/api/email-reverse-check/batch/template', {
      params: { lang: lang, type: type },
      headers: {
        'Authorization': `Bearer ${token}`
      },
      responseType: 'blob'
    });
    
    const blob = new Blob([response.data], { type: 'application/vnd.ms-excel' });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    
    let fileName;
    if (lang === 'zh') {
      fileName = type === 'email' ? '邮件反查_Email模板.xls' : '邮件反查_Phone模板.xls';
    } else {
      fileName = type === 'email' ? 'E-mail_Backcheck_Email_Template.xls' : 'E-mail_Backcheck_Phone_Template.xls';
    }
    
    link.setAttribute('download', fileName);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
    
    if (lang === 'zh') {
      ElMessage.success('模板下载成功');
    } else {
      ElMessage.success('Template downloaded successfully');
    }
  } catch (error) {
    console.error('下载模板失败:', error);
    if (lang === 'zh') {
      ElMessage.error('模板下载失败，请稍后重试');
    } else {
      ElMessage.error('Template download failed, please try again later');
    }
  }
};
</script>

<style scoped>
.email-reverse-check-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100vh;
  overflow: hidden;
}

.main-container {
  display: flex;
  flex: 1;
  height: calc(100vh - 60px);
  overflow: hidden;
}

.content-container {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background-color: #f5f7fa;
}

.search-content {
  padding: 30px;
  background-color: #fff;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.title {
  font-size: 28px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 20px;
}

.description {
  color: #606266;
  font-size: 14px;
  max-width: 800px;
  margin: 0 auto;
}

.search-actions {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.action-button {
  margin: 0 5px;
  padding: 10px 20px;
}

.search-box {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 30px;
  width: 100%;
  max-width: 900px;
  margin-left: auto;
  margin-right: auto;
}

.search-input {
  flex: 1;
}

.search-button {
  width: 80px;
  margin-left: 10px;
}

.api-error-alert {
  margin-bottom: 20px;
}

.feature-cards {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-top: 20px;
}

.feature-card {
  display: flex;
  padding: 15px;
  background-color: #fff;
  border-radius: 8px;
  border: 1px solid #ebeef5;
}

.feature-card .icon {
  margin-right: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.blue-icon {
  color: #409eff;
  background-color: #ecf5ff;
  padding: 10px;
  border-radius: 10px;
}

.green-icon {
  color: #67c23a;
  background-color: #f0f9eb;
  padding: 10px;
  border-radius: 10px;
}

.purple-icon {
  color: #935cbd;
  background-color: #f3f0fc;
  padding: 10px;
  border-radius: 10px;
}

.orange-icon {
  color: #e6a23c;
  background-color: #fff7eb;
  padding: 10px;
  border-radius: 10px;
}

.card-content {
  flex: 1;
}

.card-title {
  font-weight: bold;
  margin-bottom: 10px;
  font-size: 16px;
}

.card-desc {
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
}

/* 搜索结果样式 */
.search-results {
  margin-top: 20px;
}

.results-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.results-header h3 {
  font-size: 18px;
  color: #303133;
  margin: 0;
}

.result-cards {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.result-card {
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  padding: 15px;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
}

.result-card:hover {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.result-header h4 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.result-source {
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 10px;
  background-color: #f0f2f5;
  color: #606266;
}

.result-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-row {
  display: flex;
  align-items: center;
}

.info-label {
  min-width: 100px;
  font-weight: bold;
  color: #606266;
  font-size: 14px;
}

.info-value {
  flex: 1;
  color: #303133;
  font-size: 14px;
  word-break: break-all;
}

.highlight {
  color: #409eff;
  font-weight: bold;
}

.copy-btn {
  margin-left: 10px;
  padding: 4px 8px;
  font-size: 12px;
}

.load-more {
  margin-top: 20px;
  text-align: center;
}

.no-results {
  margin-top: 40px;
  text-align: center;
}

.loading-container {
  margin-top: 20px;
  padding: 20px;
}

/* 批量反查按钮样式 */
.batch-search-btn {
  margin-left: 10px;
}

/* 批量反查对话框样式 */
.batch-dialog-content {
  padding: 10px 0;
}

.batch-dialog-content p {
  margin: 8px 0;
  line-height: 1.6;
  font-size: 14px;
}

/* 上传组件样式优化 */
:deep(.el-upload-dragger) {
  padding: 40px 20px;
}

:deep(.el-icon--upload) {
  font-size: 48px;
  color: #409eff;
  margin-bottom: 16px;
}

:deep(.el-upload__text) {
  font-size: 14px;
  color: #606266;
}

:deep(.el-upload__text em) {
  color: #409eff;
  font-style: normal;
}

:deep(.el-upload__tip) {
  margin-top: 10px;
  font-size: 12px;
  color: #909399;
}
</style> 
